import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:gin_vue_admin_web/exports.dart';
import 'package:gin_vue_admin_web/models/simple_model.dart';
import 'package:gin_vue_admin_web/providers/system/system_riverpod.dart';
import 'package:gin_vue_admin_web/util/export_util.dart';
import 'package:gin_vue_admin_web/widgets/asyncvalue_widget.dart';
import 'package:gin_vue_admin_web/widgets/el_pagination.dart';
import 'package:syncfusion_flutter_datagrid/datagrid.dart';

import '../../layout/export_layout.dart';
import '../../local/dimens.dart';
import '../../models/models.dart';
import '../../router/router.dart';
import '../../theme/exports_theme.dart';
import '../../widgets/export_widget.dart';

class ApiPage extends StatefulWidget {
  const ApiPage({super.key});

  @override
  State<ApiPage> createState() => _ApiPageState();
}

class _ApiPageState extends State<ApiPage> {
  final params = GetApiListParams();

  final completer = Completer();

  final titles = [
    const TitleData(title: "ID", key: "id", width: 50),
    const TitleData(title: "路径", key: "path"),
    const TitleData(title: "分组", key: "apiGroup"),
    const TitleData(title: "请求方法", key: "method"),
    const TitleData(title: "描述", key: "description"),
    const TitleData(title: "操作", key: "buttons", width: 200)
  ];

  final buttons = [
    (title: "编辑", icon: Icons.edit),
    (title: "删除", icon: Icons.delete),
  ];

  final authorityId = ObjectWrap();
  final dataController = DataGridController();
  @override
  Widget build(BuildContext context) {
    final lang = context.L!;
    return DefaultLayout(
      route: RoutePath.api,
      child: Consumer(builder: (context, ref, c) {
        return PageContentCard(
          footer: FutureBuilder(
            future: completer.future,
            builder: (BuildContext context, AsyncSnapshot<dynamic> snapshot) {
              if (snapshot.hasData && snapshot.data is PageListData) {
                final pageData = snapshot.data as PageListData;
                return ElPagination(
                  total: pageData.total ?? 1,
                  pageSize: pageData.pageSize ?? 1,
                  currentPage: 1,
                  onCurrentChange: (page) {
                    params.page = page;
                    ref.invalidate(getApiListProvider(params));
                  },
                  showSizeChanger: true,
                  onSizeChange: (newSize) {
                    // 处理页面大小变化
                    params.limit = newSize;
                    ref.invalidate(getApiListProvider(params));
                  },
                  showQuickJumper: true,
                  showTotal: true,
                  pagerCount: 7,
                );
              }
              return Text("loading");
            },
          ),
          header: HeaderTable(
            left: [
              FilledButton.icon(
                onPressed: () {

                },
                label: const Text("新增"),
                style: Styles.getRoundFillShape(),
                icon: const Icon(
                  Icons.add,
                  size: Sizes.iconWidth,
                ),
              ),
              const Gap.h(10),
              FilledButton.icon(
                onPressed: () {
                  final ids = dataController.selectedRows.map((element) {
                    return (element
                        .getCells()
                        .firstWhere((e) => e.columnName == "buttons")
                        .value as ApiModel)
                        .id;
                  }).toList();
                  if (ids.isEmpty) {
                    AppUtils.showWebToast("请选择");
                    return;
                  }
                  ShowUtils.showDialog(
                    context,
                    const WebTipDialog(title: "此操作将永久删除, 是否继续?"),
                    btnOkOnPress: () {
                      // final future =
                      // ref.read(deleteOplByIdsProvider(ids).future);
                      // ref
                      //     .read(loadingStateProvider)
                      //     .whileLoading(() => future)
                      //     .then((value) {
                      //   ref.invalidate(getApiListProvider(params));
                      //   userAppRouter().pop();
                      // });
                    },
                    width: 500,
                  );
                },
                label: const Text("删除"),
                style: Styles.getRoundFillShape().copyWith(
                    backgroundColor: Styles.resolveWithStates(Colors.red)),
                icon: const Icon(
                  Icons.delete,
                  size: Sizes.iconWidth,
                ),
              ),
            ],
          ),
          child: AsyncValueWidget(ref.watch(getApiListProvider(params)),
              builder: (value) {
            final items = (value?.list as List<ApiModel>?) ?? [];
            if (!completer.isCompleted) {
              completer.complete(value);
            }
            return DataTableListPage(
              items: items,
              dataGridController: dataController,
              titles: titles,
              cellBuilder: (DataGridCell<dynamic> e) {
                if (e.columnName == "buttons") {
                  return Builder(builder: (context) {
                    return Center(
                      child: OverflowBar(
                        children: buttons
                            .map((e) => TextButtonWithIconX(
                                  onPressed: () {
                                    Scaffold.of(context).openEndDrawer();
                                  },
                                  label: Text(e.title),
                                  style: context
                                      .appExtensionTheme?.textButtonStyle,
                                  icon: Icon(
                                    e.icon,
                                    size: 20,
                                  ),
                                ))
                            .toList(),
                      ),
                    );
                  });
                }
                return Center(child: Text("${e.value}"));
              },
              rowsBuilder: () {
                return items
                    .map((e) => DataGridRow(cells: [
                          DataGridCell<int>(columnName: 'id', value: e.id),
                          DataGridCell<String>(
                              columnName: 'path', value: e.path),
                          DataGridCell<String>(
                              columnName: 'apiGroup', value: e.apiGroup),
                          DataGridCell<String>(
                              columnName: 'method', value: e.method),
                          DataGridCell<String>(
                              columnName: 'description', value: e.description),
                          DataGridCell<ApiModel>(
                              columnName: 'buttons', value: e),
                        ]))
                    .toList();
              },
            );
          }),
        );
      }),
    );
  }
}
